package com.tools.cleanmaster.utils;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.annotation.IntRange;

/**
 * desc:
 * date: 2018/3/2
 * author: ancun
 */

public class ImageUtil {

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static Bitmap convertToBlurAndBright(Context context, Bitmap sourceBmp, @IntRange(from = 1, to = 25) int radius, int scale) {

        //缩小图片
        int width = Math.round(sourceBmp.getWidth() / scale);
        int height = Math.round(sourceBmp.getHeight() / scale);
        Bitmap scaleBmp = Bitmap.createScaledBitmap(sourceBmp, width, height, false);

        //调整图片亮度
        Bitmap brightBmp = Bitmap.createBitmap(width, height, scaleBmp.getConfig());
        Canvas canvas = new Canvas(brightBmp);
        Paint paint = new Paint();
        int brightness = -80; //RGB偏移量，变暗为负数
        ColorMatrix matrix = new ColorMatrix();
        matrix.set(new float[]{1, 0, 0, 0, brightness, 0, 1, 0, 0, brightness, 0, 0, 1, 0, brightness, 0, 0, 0, 1, 0});
        paint.setColorFilter(new ColorMatrixColorFilter(matrix));
        canvas.drawBitmap(scaleBmp, 0, 0, paint);

        //做高斯模糊
        RenderScript renderScript = RenderScript.create(context);

        // Allocate memory for Renderscript to work with
        final Allocation input = Allocation.createFromBitmap(renderScript, brightBmp);
        final Allocation output = Allocation.createTyped(renderScript, input.getType());

        // Load up an instance of the specific script that we want to use.
        ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(renderScript, Element.U8_4(renderScript));
        scriptIntrinsicBlur.setInput(input);

        // Set the blur radius
        scriptIntrinsicBlur.setRadius(radius);

        // Start the ScriptIntrinisicBlur
        scriptIntrinsicBlur.forEach(output);

        // Copy the output to the blurred bitmap
        output.copyTo(brightBmp);

        renderScript.destroy();

        return brightBmp;
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static Bitmap convertToBlurAndBright(Context context, Bitmap source) {
        //据前辈们经验，一般 scale = 8 为佳。
        return convertToBlurAndBright(context, source, 25, 8);
    }
}
